<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索 添加 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入姓名(可以少但是不要多)"
            v-model="queryInfo.query"
            clearable="true"
            @clear="likeClear"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加次级账号</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <!-- stripe: 斑马条纹
        border：边框-->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="levelValue" label="等级"></el-table-column>
        <el-table-column prop="money" label="金钱"></el-table-column>
        <el-table-column label="是否停用">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isDelete"
              :active-value="1"
              :inactive-value="0"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              circle
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              circle
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="角色分配"
              :enterable="false"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                circle
                @click="showSetRole(scope.row)"
              ></el-button>
            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加下级账号" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体 -->
      <el-form
        :model="addUserForm"
        ref="addUserFormRef"
        :rules="addUserFormRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addUserForm.name"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addUserForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <!-- <el-form-item label="验证码" prop="code">
          <el-input placeholder="请输入内容" v-model="addUserForm.code" class="input-with-select">
            <el-button
              slot="append"
              type="primary"
              :disabled="addIsCode"
              @click="addGetCode"
              style="width:120px"
            >{{text}}</el-button>
          </el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="addCheckUserRepetition">检查重复</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser" :disabled="checkAddSecondaryUserButton()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改账号 信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="updateUserForm"
        ref="editUserFormRef"
        :rules="editUserFormRules"
        label-width="70px"
      >
        <el-form-item label="旧姓名" prop="name">
          <el-input v-model="showUserForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="新姓名" prop="name">
          <el-input v-model="updateUserForm.name"></el-input>
        </el-form-item>
        <el-form-item label="旧用户名" >
          <el-input v-model="showUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="新用户名" prop="username">
          <el-input v-model="updateUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="updateUserForm.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editUser(showUserForm.id)"
        >确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import {
  editUser,
  addCheckUserRepetition,
  getSecondaryList,
  userStateChanged,
  addSecondary,
  showEditDialog,
  getSecondaryInfoById,
  getUserLikeList,
} from "@/utils/SupervisorApi";
import { getCode } from "@/utils/Api";
export default {
  data() {
    var checkChinese = (rule, value, callback) => {
      const regChinese = /[^\u4e00-\u9fa5]/;
      if (regChinese.test(value)||value == null ||value == '') {
        return callback();
      }
      callback(new Error("请不要输入中文"));
    };
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法邮箱"));
    };
    // 自定义手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      // 返回一个错误提示
      callback(new Error("请输入合法的手机号码"));
    };
    return {
      text: "获取验证码",
      addIsCode: false,
      //添加下级用户的按钮是否可用
      addSecondaryUser: {
        checkUsername: true,
        checkPhone: true,
      },
      // 获取用户列表查询参数对象
      queryInfo: {
        query: "",
        // 当前页数
        pageNum: 1,
        // 每页显示多少数据
        pageSize: 5,
      },
      userlist: [],
      total: 0,
      // 添加用户对话框
      addDialogVisible: false,
      // 用户添加
      addUserForm: {
        username: "",
        name: "",
        password: "",
        phone: "",
        code: "",
      },
      showUserForm: {
        id: "",
        username: "",
        name: "",
        password: "",
        phone: "",
      },
      updateUserForm: {
        id: "",
        username: "",
        name: "",
        password: "",
        phone: "",
      },
      // 用户添加表单验证规则
      addUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "用户名的长度在2～20个字",
            trigger: "blur",
          },
          {
            validator: checkChinese,
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 6,
            max: 18,
            message: "用户密码的长度在6～18个字",
            trigger: "blur",
          },
          {
            validator: checkChinese,
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
          {
            validator: checkChinese,
            trigger: "blur",
          },
        ],
      },

      // 修改用户
      editDialogVisible: false,
      editUserForm: {},
      // 编辑用户表单验证
      editUserFormRules: {
        username: [
          {
            min: 2,
            max: 20,
            message: "用户名的长度在2～20个字",
            trigger: "blur",
          },
          {
            validator: checkChinese,
            trigger: "blur",
          },
        ],
        password: [
          {
            min: 6,
            max: 18,
            message: "用户密码的长度在6～18个字",
            trigger: "blur",
          },
          {
            validator: checkChinese,
            trigger: "blur",
          },
        ],
      },

    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    likeClear() {
      this.queryInfo.query = "";
      this.queryInfo.pageNum = 1;
      this.getUserList();
    },
    async addGetCode() {
      if (this.addUserForm.phone == "") {
        return this.$message.error(手机号不能为空);
      }
      const { data: res } = await getCode({
        phone: this.addUserForm.phone,
        type: 2,
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message);
      }
      this.$message.success("短信已成功发送");
      this.addOutTime();
    },
    addOutTime() {
      this.text = 60;
      this.addIsCode = true;
      const outTime = setInterval(() => {
        this.text = this.text - 1;
        if (this.text == 0) {
          this.text = "获取验证码";
          clearInterval(outTime);
          this.addIsCode = false;
        }
      }, 1000);
    },
    // 修改用户信息
    editUser(id) {
      // 提交请求前，表单预验证
      this.$refs.editUserFormRef.validate(async (valid) => {
        console.log(valid);

        if (!valid) {
          this.$message.error("填写内容有误请按要求填写");
          return;
        }
        this.updateUserForm.id = id;
        const { data: res } = await editUser(this.updateUserForm);
        if (res.meta.status !== 200) {
          this.$message.error("更新用户信息失败！");
        }
        // 隐藏添加用户对话框
        this.editDialogVisible = false;
        this.$message.success("更新用户信息成功！");
        this.getUserList();
      });
    },
    async updateCheckUserRepetition() {
      this.$refs.editUserFormRef.validate(async (valid) => {
        console.log(valid);

        if (!valid) {
          this.$message.error("填写内容有误请按要求填写");
          return;
        }
        const { data: res } = await addCheckUserRepetition(this.updateUserForm);
        if (res.data) {
          this.$message.error("账号名或者手机号重复请重新输入");
        } else {
          this.addSecondaryUser.checkPhone = false;
          this.addSecondaryUser.checkUsername = false;
          console.log(this.addSecondaryUser.checkUsername);
          this.$message({
            message: "账号信息可用",
            type: "success",
          });
        }
      });
    },
    async addCheckUserRepetition() {
      if (this.addUserForm.phone == "") {
        return this.$message.error("请填写手机号");
      }
      const { data: res } = await addCheckUserRepetition(this.addUserForm);
      if (res.data) {
        this.$message.error("账号名或者手机号重复请重新输入");
      } else {
        this.addSecondaryUser.checkPhone = false;
        this.addSecondaryUser.checkUsername = false;
        console.log(this.addSecondaryUser.checkUsername);
        this.$message({
          message: "账号信息可用",
          type: "success",
        });
      }
    },
    checkAddSecondaryUserButton() {
      return (
        this.addSecondaryUser.checkUsername || this.addSecondaryUser.checkPhone
      );
    },
    async getUserList() {
      const { data: res } = await getSecondaryList(this.queryInfo);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败！");
      }
      this.userlist = res.data.userList;
      this.total = res.data.total;
    },
    // 监听 pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.queryInfo.pageNum = 1;
      this.getUserList();
    },
    // 监听 页码值 改变事件
    handleCurrentChange(newSize) {
      this.queryInfo.pageNum = newSize;
      this.getUserList();
    },
    // 监听 switch开关 状态改变
    async userStateChanged(userInfo) {
      const { data: res } = await userStateChanged({
        id: userInfo.id,
        isDelete: userInfo.isDelete,
      });
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功！");
    },
    // 监听 添加用户对话框的关闭事件
    addDialogClosed() {
      this.addSecondaryUser.checkUsername = true;
      this.addSecondaryUser.checkPhone = true;
      this.$refs.addUserFormRef.resetFields();
    },
    // 添加用户
    addUser() {
      // 提交请求前，表单预验证
      this.$refs.addUserFormRef.validate(async (valid) => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return;
        const { data: res } = await addSecondary(this.addUserForm);
        if (res.meta.status === 200) {
          this.$message.success("添加用户成功！");
        } else {
          this.$message.error("添加用户失败");
        }
        // 隐藏添加用户对话框
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    // 获取编辑用户信息 这里要修改代码
    async showEditDialog(id) {
      const { data: res } = await getSecondaryInfoById({ id: id });
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败！");
      }
      this.showUserForm = res.data; //放弃显示用户
      this.editDialogVisible = true;
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.addSecondaryUser.checkUsername = true;
      this.addSecondaryUser.checkPhone = true;
      this.$refs.editUserFormRef.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
</style>
